package ats.org.DAO;


import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;


public class GenericDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	public EntityManager getEntityManager() {
		return em;
	}

	/*public EntityManager buildEntityManager(){
		EntityManagerFactory emf;
		//emf = Persistence.createEntityManagerFactory("HRUnit");
		em = emf.createEntityManager();
		return em;
	}*/
	
	public <T> List<T> findAll(Class<T> entity){
		em = getEntityManager();
		TypedQuery<T> tq = em.createNamedQuery(entity.getSimpleName() + ".findAll", entity);
		return tq.getResultList();
	}
	
	public <T> T findByKey(Class<T> entity, Object primaryKey){
		em = getEntityManager();
		return em.find(entity, primaryKey);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> List<T> findByNamedQuery(Class<T> entity, String queryName, Map<String, ?> paramMap){
		em = getEntityManager();
		//System.out.println(entity.getSimpleName() + "." + queryName);
		TypedQuery<T> tq = em.createNamedQuery(entity.getSimpleName() + "." + queryName, entity);
		for (Parameter param : tq.getParameters()) {
			tq.setParameter(param, paramMap.get(param.getName()));
		}
		return tq.getResultList();
	}
	
	public <T> List<?> findByNamedQuery(Class<T> entity, String queryName){
		em = getEntityManager();
		Query q = em.createNamedQuery(entity.getSimpleName() + "." + queryName);
		return q.getResultList();
	}
	
	public <T> T mergeEntity(T entity){
		em = getEntityManager();
		return em.merge(entity);
	}
	
	public <T> void Add(T entity){
		em = getEntityManager();
		em.persist(entity);
	}

}

